﻿using CacheManager.IOC;
using Jil;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace CacheManager
{
    public class DistributedCacheManager : ICacheManager
    {
        private static IDistributedCache Instance => AspectCoreContainer.Resolve<IDistributedCache>();
        public string Get(string key)
        {
            if (RedisHelper.Exists(key))
            {
                return RedisHelper.Get(key);
            }
            return null;
        }

        public async Task<string> GetAsync(string key)
        {
            if (await RedisHelper.ExistsAsync(key))
            {
                var content = await RedisHelper.GetAsync(key);
                return content;
            }
            return null;
        }

        public T Get<T>(string key)
        {
            var value = Get(key);
            if (!string.IsNullOrEmpty(value))
                return JSON.Deserialize<T>(value);
            return default(T);
        }

        public async Task<T> GetAsync<T>(string key)
        {
            var value = await GetAsync(key);
            if (!string.IsNullOrEmpty(value))
            {
                return JSON.Deserialize<T>(value);
            }
            return default(T);
        }

        public void Set(string key, object data, int expiredSeconds)
        {
            RedisHelper.Set(key, JSON.Serialize(data), expiredSeconds);
        }

        public async Task<bool> SetAsync(string key, object data, int expiredSeconds)
        {
            return await RedisHelper.SetAsync(key, JSON.Serialize(data), expiredSeconds);
        }
    }
}
